package logic

import (
	"context"
	"errors"
	"novel/models/mysql"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelAddLogic {
	return &NovelAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 小说添加
func (l *NovelAddLogic) NovelAdd(in *novelrpc.NovelAddRequest) (*novelrpc.NovelAddResponse, error) {
	// todo: add your logic here and delete this line
	var firstNovel mysql.User
	err := firstNovel.FirstNovelByUserId(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("用户不存在,不允许添加")
	}
	novel := &mysql.Novel{
		UserId:    in.UserId,
		Title:     in.Title,
		NovelType: in.NovelType,
		Label:     in.Label,
		Content:   in.Content,
	}
	if in.Title == "" || in.NovelType == "" || in.Content == "" {
		return nil, errors.New("必填字段（标题、分类、简介）")
	}
	err = novel.NovelAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("添加失败")
	}
	return &novelrpc.NovelAddResponse{
		NovelId: int64(novel.ID),
	}, nil
}
